<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>录制canvas视频</title>
  <style>
    html,
    body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }

    .box {
      display: flex;
      justify-content: space-around;
      align-items: center;
    }

    #videoContainer {
      display: none;
      border: 1px solid red;
    }

    #dot {
      width: 10px;
      height: 10px;
      background: red;
      border-radius: 50%;
      margin: 10px 20px;
      display: none;
      animation: shan 1s infinite;
    }

    @keyframes shan {
      0% {
        opacity: 1;
      }

      100% {
        opacity: 0;
      }
    }
  </style>
</head>

<body>
  <div class="box">
    <div id="canvasBox">
      <div id="dot"></div>
      <canvas width="600" height="600"></canvas>
    </div>
    <div id="videoContainer">
      <h2>录制的视频</h2>
      <video src="" loop="true" autoplay controls width="300" height="300"></video>
    </div>
  </div>
  <div style="display: flex; justify-content: center;margin-top: 40px;">
    <button id="start">开始录制</button>
    <button id="stop" style="margin-left: 40px;">结束录制</button>
  </div>
</body>
<script>
  const canvas = document.querySelector('canvas');
  const ctx = canvas.getContext('2d');
  const { width, height } = canvas;

  ctx.fillStyle = 'red';

  function draw(rotation = 0) {
    ctx.clearRect(0, 0, 1000, 1000);
    ctx.save();
    ctx.translate(width / 2, height / 2);
    ctx.rotate(rotation);
    ctx.translate(-width / 2, -height / 2);
    ctx.beginPath();
    ctx.rect(200, 200, 200, 200);
    ctx.fill();
    ctx.restore();
  }

  function update(t) {
    draw(t / 500);
    requestAnimationFrame(update);
  }
  update(0);

  //接下来，我们将这个效果录制下来，假设我们录制6秒的视频，首先我们要获取MediaStream对象
  const stream = canvas.captureStream();

  // 然后，我们创建一个MediaRecorder：
  const recorder = new MediaRecorder(stream, { mimeType: 'video/webm' });

  // 接着我们可以注册ondataavailable事件，将数据记录下来：
  const data = [];
  recorder.ondataavailable = function (event) {
    if (event.data && event.data.size) {
      data.push(event.data);
    }
  };

  // 接着我们可以注册ondataavailable事件，将数据记录下来：
  recorder.onstop = () => {
    const url = URL.createObjectURL(new Blob(data, { type: 'video/webm' }));
    document.querySelector("#videoContainer").style.display = "block";
    document.querySelector("video").src = url;
  };


  document.querySelector("#start").onclick = function () {
    document.querySelector("#canvasBox").style.border = '1px solid red';
    document.querySelector("#dot").style.display = 'block';
    recorder.start();
  }
  document.querySelector("#stop").onclick = function () {
    document.querySelector("#canvasBox").style.border = 'none';
    document.querySelector("#dot").style.display = 'none';
    recorder.stop();
  }






</script>

</html>